package com.zheng.upms.rpc.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.zheng.common.annotation.BaseService;
import com.zheng.common.base.BaseServiceImpl;
import com.zheng.upms.dao.mapper.UpmsRolePermissionMapper;
import com.zheng.upms.dao.model.UpmsRolePermission;
import com.zheng.upms.dao.model.UpmsRoleSystem;
import com.zheng.upms.rpc.api.UpmsRolePermissionService;
import com.zheng.upms.rpc.api.UpmsRoleSystemService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 角色权限关联表 服务实现类
 * </p>
 *
 * @author likun
 * @since 2017-12-29
 */
@Service
@Transactional
@BaseService
public class UpmsRolePermissionServiceImpl extends BaseServiceImpl<UpmsRolePermissionMapper, UpmsRolePermission> implements UpmsRolePermissionService {
    private static Logger _log = LoggerFactory.getLogger(UpmsRolePermissionServiceImpl.class);
    @Autowired
    private UpmsRoleSystemService roleSystemService;

    @Override
    public int rolePermission(JSONArray systemArray, JSONArray permissionArray, Integer roleId) {
        List<Integer> deleteIds = new ArrayList<>();
        for (int i = 0; i < permissionArray.size(); i++) {
            JSONObject json = permissionArray.getJSONObject(i);
            if (!json.getBoolean("checked")) {
                deleteIds.add(json.getIntValue("id"));
            } else {
                // 新增权限
                UpmsRolePermission upmsRolePermission = new UpmsRolePermission();
                upmsRolePermission.setRoleId(roleId);
                upmsRolePermission.setPermissionId(json.getInteger("id"));
                super.baseMapper.insert(upmsRolePermission);
            }
        }
        // 删除权限
        if (deleteIds.size() > 0) {
            super.baseMapper.delete(new EntityWrapper<UpmsRolePermission>().in("permission_id", deleteIds).eq("role_id", roleId));
        }
        deleteIds = new ArrayList<>();
        for (int i = 0; i < systemArray.size(); i++) {
            JSONObject json = systemArray.getJSONObject(i);
            if (!json.getBoolean("checked")) {
                deleteIds.add(json.getIntValue("id"));
            } else {
                // 新增权限
                UpmsRoleSystem upmsRoleSystem = new UpmsRoleSystem();
                upmsRoleSystem.setRoleId(roleId);
                upmsRoleSystem.setSystemId(json.getInteger("id"));
                roleSystemService.insert(upmsRoleSystem);
            }
        }
        // 删除权限
        if (deleteIds.size() > 0) {
            roleSystemService.delete(new EntityWrapper<UpmsRoleSystem>().in("system_id", deleteIds).eq("role_id", roleId));
        }
        return permissionArray.size();
    }
}
